package com.ruoyi.app.common;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by xiaoban on 2019/10/10.
 */
@Component
public class SmsUtil {
    @Autowired
    RedisCache RedisUtils;

    @Value("${Sms.accessKeyId}")
    private String accessKeyId;
    @Value("${Sms.accessSecret}")
    private String accessSecret;
    @Value("${Sms.sign}")
    private String sign;
    @Value("${Sms.templateCode}")
    private String templateCode;

    private  Integer CheckRedisNull(String phone) {
        return RedisUtils.getCacheObject("registerNum:phone" + phone) == null ? null : Integer.valueOf(RedisUtils.getCacheObject("registerNum:phone" + phone));
    }

    private  String CheckRedisNumNull(String phone) {
        return RedisUtils.getCacheObject("registerNum:phone" + phone) == null ? "1" : String.valueOf(Integer.parseInt(RedisUtils.getCacheObject("registerNum:phone" + phone)) + 1);
    }

    public AjaxResult sendSms(String phone) {
        //判断次数
        Integer SmsNum = CheckRedisNull(phone);
        if (!StringUtils.isEmpty(SmsNum) && SmsNum >= 50) {
            return AjaxResult.error("今日短信次数用尽");
        }
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("SignName", sign);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("TemplateCode", templateCode);
        String code = String.valueOf(new Random().nextInt(9000) + 1000);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);

        } catch (ClientException e) {
            e.printStackTrace();
        }
        //增加次数
        RedisUtils.setCacheObject("registerNum:phone" + phone, CheckRedisNumNull(phone), 86400,TimeUnit.SECONDS);
        RedisUtils.setCacheObject("register:phone" + phone, code, 3000, TimeUnit.SECONDS);
        return AjaxResult.success();
    }
}
